package net.kazed.nextaction.tools;

import java.util.Date;

import net.kazed.nextaction.R;
import net.kazed.nextaction.database.serialize.BackupFile;
import net.kazed.nextaction.database.serialize.BackupFileSummary;
import net.kazed.nextaction.database.serialize.BackupSummaryCursor;
import android.app.ListActivity;
import android.content.ContentUris;
import android.content.Context;
import android.content.Intent;
import android.content.res.Resources;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;

/**
 * Display list of backup files.
 */
public class BackupListActivity extends ListActivity {

    public static final String SELECTED_ITEM = "SELECTED_ITEM";

    private static final int BACKUP_ADD = Menu.FIRST;
    private static final int BACKUP_IMPORT = BACKUP_ADD + 1;

    private static final String TAG = "BackupListActivity";
    private static final int VIEW_ITEM = 1;

    private Cursor cursor;
    
    private BusyDialog busyDialog;

    @Override
    public void onCreate(Bundle icicle) {
        super.onCreate(icicle);
        setContentView(R.layout.backup_list);
        setDefaultKeyMode(DEFAULT_KEYS_SHORTCUT);

        determineBackupFiles();
    }

    @Override
    protected void onResume() {
        super.onResume();
    }

    private void determineBackupFiles() {
        cursor = managedQuery(BackupFileSummary.CONTENT_URI, null, null, null, null);
        setListAdapter(new BackupListAdapter(this, R.layout.list_item_view, cursor));
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
       super.onActivityResult(requestCode, resultCode, data);
       Log.d(TAG, "onActivityResult");
       determineBackupFiles();
       onContentChanged();
    }
    
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        Resources resources = getResources();
        if (Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())) {
            menu.add(0, BACKUP_IMPORT, 0, resources.getString(R.string.menu_import_backup)).setIcon(
                            android.R.drawable.ic_menu_upload).setAlphabeticShortcut('i');
        }
        String menuName = resources.getString(R.string.menu_add_backup);
        MenuItem item = menu.add(0, BACKUP_ADD, 0, menuName).setIcon(
                android.R.drawable.ic_menu_add);
        item.setAlphabeticShortcut('n');
        return super.onCreateOptionsMenu(menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
        case BACKUP_ADD:
            busyDialog = new BusyDialog(this, new BusyDialog.BackgroundAction() {
                public void execute() {
                    getContentResolver().insert(BackupFile.CONTENT_URI, null);
                }
            }, new BusyDialog.DoneAction() {
                public void execute(Exception e) {
                    determineBackupFiles();
                    onContentChanged();
                }
            });
            busyDialog.execute(R.string.backup_busy_title, R.string.backup_busy_message);
            break;
        case BACKUP_IMPORT:
            // get filename from dialog
            Intent intent = new Intent(Intent.ACTION_PICK, BackupFile.CONTENT_EXTERNAL_URI);
            startActivityForResult(intent, VIEW_ITEM);
//            getContentResolver().update(BackupFile.CONTENT_URI, null, GtdProvider.BACKUP_IMPORT_FROM_SD_CARD, null);
//            determineBackupFiles();
//            onContentChanged();
            break;
        }
        return super.onOptionsItemSelected(item);
    }
    
    @Override
    protected void onListItemClick(ListView l, View v, int position, long id) {
        Log.d(TAG, "onListItemClick" + position);
        if (cursor.moveToPosition(position)) {
            long created = cursor.getLong(BackupSummaryCursor.INDEX_ID);
            Uri itemUri = ContentUris.withAppendedId(BackupFile.CONTENT_ITEM_URI, created);
            Intent intent = new Intent(Intent.ACTION_VIEW, itemUri);
            startActivityForResult(intent, VIEW_ITEM);
        }
    }
    

    private class BackupListAdapter extends SimpleCursorAdapter {
        
        private static final String cTag = "TaskListAdapter";

        public BackupListAdapter(Context context, int listItemLayoutId, Cursor cursor) {
           super(context, listItemLayoutId, cursor, new String[] { BackupFileSummary.COLUMN_ID },
                    new int[] { R.id.name });
        }
        
        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
           Log.d(cTag, "getView position=" + position + ". Old view=" + convertView);
           BackupListItemView backupListItemView = null;
           if (convertView instanceof BackupListItemView) {
               backupListItemView = (BackupListItemView) convertView;
           } else {
               backupListItemView = new BackupListItemView(parent.getContext(), true);
           }
           Cursor cursor = getCursor();
           if (cursor.moveToPosition(position)) {
               long created = getCursor().getLong(0);
               BackupFileSummary backupFileSummary = new BackupFileSummary(new Date(created), 0, 0);
               backupListItemView.updateView(backupFileSummary);
           }
           return backupListItemView;
        }

     }

}